package com.kaifamiao.reqeust;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Iterator;

@WebServlet("/parse")
public class ParseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取请求行(request line)中的数据
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String protocol = request.getProtocol();
        // 获取请求头(request header)中的数据
        Enumeration<String> names = request.getHeaderNames(); // 获取所有请求头字段名称
        Iterator<String> it = names.asIterator();
        // 获得用于读取请求体(request body)数据的字节输入流
        ServletInputStream in = request.getInputStream();
        Reader reader = new InputStreamReader( in, StandardCharsets.UTF_8 );
        BufferedReader br = new BufferedReader( reader );

        System.out.printf( "%s %s %s\r\n", method, uri, protocol );
        while( it.hasNext() ){
            String name = it.next(); // 得到单个请求头字段名称
            String value = request.getHeader( name ); // 根据请求头字段名称获取值
            System.out.printf( "%s: %s\r\n", name, value );
        }
        System.out.printf("\r\n");

        String str = null ;
        while( (str = br.readLine() ) != null ){
            System.out.println( str );
        }

        response.setCharacterEncoding( "UTF-8" );
        // response.setContentType( "text/html; charset=UTF-8" );
        // 设置响应头中`content-type`字段的值
        response.setHeader( "content-type" , "text/html; charset=UTF-8" );
        PrintWriter out = response.getWriter();
        out.println( "<h3>去服务器的控制台查看结果吧</h3>");
    }

}
